var categoryModal = function(p){
	var that = {};
	
	var wrapper,container,item_view,trigger,ptree,title,hidden;
	wrapper = (p.container) ? p.container+"w" : "#modal_container";
	container = (p.container) ? p.container : "#selected_category";
	item_view = (p.container) ? p.container + "_item_view" : "#item_view";
	title = (p.title) ? p.title : "選択してください";
	hidden = (p.hidden) ? p.hidden : "category";
	
	//モーダルウインドウを格納するノードを追加して、対象モジュールをload
	
	var html = '<div id="' + wrapper.replace('#','') + '" class="mcon">';
	html += '<span class="close_btn"><a href="javascript:;">b</a></span>';
	html += '<h3>' + title + '</h3>';
	html += '<div id="' + item_view.replace('#','') + '"></div></div>';
	
	$('body').append(html);
	$(item_view).load(p.url,
	function(){
		if(p.mode == "tree"){
		
			trigger = (p.trigger) ? p.trigger : ".btn_category";
			ptree =(p.container) ? p.container+'_tree' : "#category";
			$(".tree_left > ul",item_view).attr('id',ptree.replace('#',''));
			setTreeView(ptree);
			
		}else if(p.mode == "table") {
			
			trigger = (p.trigger) ? p.trigger : "#btn_additem, .rank, .mt_trigger";
		}
		
		$(wrapper).draggable({handle:"h3"});
		that.setModal();
	});
	
	that.setModal = function(){
		
		//アイテム削除イベントの設定
		that.setDelClick();

		if(p.mode == "tree"){
			$(trigger).click(function(){
				that.toggleModal(true);
			});
			
			$(item_view + " .cid").click(function(){
				if(!$(this).hasClass("selected")){
					$(this).addClass("selected");
					
					var html = '<li name="' + $(this).parent().attr('id') + '"><a href="javascript:;" class="delete_category">削除</a>' + $(this).text() + '</li>';

					$(item_view + ' .tree_right ul').append(html);
					that.setDelClick();
				}
			});
			$(item_view + ' .tree_right p a').click(function(){
				that.toggleModal(false);
				var ids = "";
				$(item_view + ' .tree_right ul li').each(function(){
					ids += $(this).attr("name") + ",";
				});
				that.setCategory( ids );
			});
		}else{
			$(trigger).click(function(){
				$('#rank_no').val( $(this).parent().attr('id') );
				that.toggleModal(true);
			});
			$("tbody tr",item_view).hover(
				function(){
					$(this).addClass("hover");
				},
				function(){
					$(this).removeClass("hover");
				}
			);
			$("tbody tr",item_view).click(function(){
				that.toggleModal(false);
				that.set_item( $(".btn_item",this).attr('id') );
			});
			$('.del_cell_item').click(function(){
				if($('#item_id' + $(this).parent().attr('id') ).size() > 0){
					$('#item_id' + $(this).parent().attr('id') ).val('');
					$('#item_name' + $(this).parent().attr('id') ).val('');
				}else {
					$('input[type=text]',$(this).parent()).val("");
				}
			});
		}
	};
	
	that.toggleModal = function(s){
		if(s == true){
			//scrollToTop();
			
			if($(item_view + ' .tree_right').size() > 0){
				$(item_view + ' .tree_right ul').html("");
				$(item_view + ' .cid').removeClass("selected");
			}
			
			$('body').append('<div id="modal_background">&nbsp;</div>');
			$('#modal_background').fadeIn(300).height($(document).height());
			$(wrapper).show().css({"position":"absolute","opacity":0,'top':($(document).scrollTop())+'px'}).animate({"opacity":1,"top":($(document).scrollTop()+50)+"px"},300);
			$('#modal_background , .close_btn').click(function(){
				that.toggleModal(false);
			});
		}else {
			$('#modal_background').fadeOut(300,function(){$(this).remove();});
			$(wrapper)
				.css({"position":"absolute"})
				.animate({"opacity":0,"top":$(document).scrollTop()+'px'},300,
				function(){
					$(this).hide();
				});
		}
	};

	//--- for treeView --------------------------------------------------------------
	that.setCategory = function(ids){
		
		if(ids != ""){
		
			ids = ids.split(",");
			
			for(var i=0; i < ids.length-1; i++ ){
				url  = "Home_getcategory_index.html?id=" + ids[i];
				
				$.ajax({
					type: 'GET',
					url: url,
					datatype: 'json',
					success: function(jsonData){
						var jsonObj = eval(jsonData);
						exist = false;
						$(container + ' li').each( function(){
							if(typeof jsonObj[0] != "undefined" && $(this).attr('id') == jsonObj[0].id ){
								exist = true;
							}
						});
						if( !exist ){
							str = '<li id="' + jsonObj[0].id + '"><a href="javascript:;" class="delete_category">削除</a> ' + jsonObj[0].name + '</li>';
							$(container).append(str).fadeIn();
							that.setDelClick();
						}
						if(i == ids.length-1){
							that.pushID();
						}
						
					},
					error: function(xhr, status, err) {
						alert(err);
					}
				});
			}
			that.sortable_category();
		}
	};
	
	that.setDelClick = function(){
		$('.delete_category').unbind().click(function(){
			$(this).parent().remove();
			if($(container + ' li').size() == 0){
				$(".th_span").remove();
			}
			//hiddenの値設定しなおし
			var arrCategory = new Array();
			$('li',container).each( function(){
				arrCategory.push( $(this).attr('id'));
			});
			$('input[name=' + hidden + ']').val(arrCategory.toString());
		});
	};
	
	that.sortable_category = function(){
		
		if($('.th_span',$(container).closest('tr')).size() == 0){
			$('th',$(container).closest('tr')).append("<span class='th_span'><br />ドラッグ&ドロップで<br />並び替え出来ます。</span>");
			$(".th_span").fadeIn(1000);
		}
		
		$(container).sortable({
			start: function(event, ui) {
				$("body").append("<div id='righttopmsg'>並べたい位置に移動して、クリックを離して下さい。</div>");
				$('#righttopmsg').show(300);
			},
			stop: function(event, ui) {
				$('#righttopmsg').fadeOut(300,function(){$(this).remove();});
			}
		});
		$(container).disableSelection();
	};
	
	//--- for tableView --------------------------------------------------------------
	that.get_item = function(id){
		
		if(p.type == "rank"){
			url  = './get_item.php?id=' + id;
				$.ajax({
					type: 'GET',
					url: url,
					datatype: 'text',
				success: function(jsonData){
					var jsonObj = eval(jsonData);
					idx = 'item_name' + $('#rank_no').val();
					$('#' + idx).val( jsonObj[0].name );
				},
				error: function(xhr, status, err) {
					alert(err);
				}
			});
		}else if(p.type == "multi"){
			url  = './get_item.php?id=' + id;
				$.ajax({
					type: 'GET',
					url: url,
					datatype: 'text',
				success: function(jsonData){
					var jsonObj = eval(jsonData);
					$(container).val( jsonObj[0].name );
				},
				error: function(xhr, status, err) {
					alert(err);
				}
			});
		}else { // for form_form.php
			url  = './get_formitem.php?id=' + id;
			$.ajax({
				type: 'GET',
				url: url,
				datatype: 'text',
				success: function(jsonData){
					var jsonObj = eval(jsonData);
					idx = 'item_name' + $('#rank_no').val();
					$('#' + idx).val( jsonObj[0].name );
	
					var table = $('#table_extra');
					var count = 0;
					$(table).find('tr').each(function() {
						count++
					});
	
					var str = '<tr>';
					str += '<td><a href="javascript:;" class="delete_category">削除</a></td>';
					str += '<th><span>項目名</span></th>';
					str += '<td>' + jsonObj[0].name + '</td>';
					str += '<th class="ques"><span>公開側質問文</span></th>';
					str += '<td class="ques_form"><input type="text" name="ex_question[' + count + ']" value="" /></td>';
					str += '<th><span>種別</span></th><td>' + jsonObj[0].type + '</td>';
					str += '<th><span>必須</span></th>';
					str += '<td><label><input type="checkbox" name="ex_neccesary[' + count + ']" value="1" /></label></td>';
					str += '<th><span>公開</span></th>';
					str += '<td>';
					str += '<label><input type="checkbox" name="ex_status[' + count + ']" value="1" checked /></label>';
					str += '<input type="hidden" name="item_id[' + count + ']" value="' + jsonObj[0].id + '" /></td></tr>';
					/*var str = '<tr><td><label><input type="checkbox" name="ex_status[' + count + ']" value="1" checked />公開</label><input type="hidden" name="item_id[' + count + ']" value="' + jsonObj[0].id + '" /></td>';
					str += '<td><dl><dt>項目名</dt><dd>' + jsonObj[0].name + '</dd><dt>公開側質問文</dt><dd><input type="text" name="ex_question[' + count + ']" value="" /></dd><dt>種別</dt><dd>' + jsonObj[0].type + '</dd><dt>必須</dt><dd><input type="checkbox" name="ex_neccesary[' + count + ']" value="1" /></dd></dl></td></tr>';*/
	
					$(table).append(str);
					sortableTable(".draggable");
					setRadioAndCheckbox();
					that.delRow();
				},
				error: function(xhr, status, err) {
					alert(err);
				}
			});
		}
	};
	
	// for form_form.php
	that.delRow = function(){
		$('.delete_category').unbind();
		$('.delete_category').click(function(){	
			var thisthis = $(this);			
			customConfirm('削除しますか？',"",$(this),function(){
				thisthis.parent().parent().remove();
				$('#table_extra tbody tr').each(function(i){
					$('input[type=text]',this).attr("name",'ex_question[' + (i) + ']');
					$('input[type=checkbox]:eq(0)',this).attr("name",'ex_neccesary[' + (i) + ']');
					$('input[type=checkbox]:eq(1)',this).attr("name",'ex_status[' + (i) + ']');
					$('input[type=hidden]',this).attr("name",'item_id[' + (i) + ']');
				});
			});
		});
	};
	
	that.set_item = function( id ){
		idx = 'item_id' + $('#rank_no').val();
		$('#' + idx).val( id );
		that.get_item( id );
	}
	
	that.pushID = function(){
		var form = $('form[name=fm]',form);
		var arrCategory = new Array();
		$('#selected_category li').each( function(){
			arrCategory.push( $(this).attr('id'));
		});
		$('input[name=' + hidden + ']').val(arrCategory.toString());
	};
	
	return that;
};